package com.hwtx.form.domain.meta;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Sets;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class FunPermCache {
    private final Cache<Long, Set<String>> noAuthCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.DAYS).build();
    private final Set<String> noAuthUrls = Sets.newHashSet();

    @Resource
    private ServerProperties serverProperties;

    public boolean isNoAuth(String url) {
        if (noAuthUrls.isEmpty()) {
            noAuthUrls.addAll(noAuthCache.asMap().values().stream().flatMap(Set::stream).toList());
        }
        return noAuthUrls.contains(url);
    }

    public boolean isNoAuth(Long formId, String url) {
        Set<String> urls = noAuthCache.getIfPresent(formId);
        return urls != null && urls.contains(url);
    }

    public void putFormNoAuth(Long formId, List<String> urls) {
        Set<String> cacheUrls = noAuthCache.getIfPresent(formId);
        if (cacheUrls == null) {
            cacheUrls = Sets.newHashSet();
        }
        String context = serverProperties.getServlet().getContextPath();
        cacheUrls.addAll(urls.stream().map(url -> {
            if (url.startsWith(context)) {
                return url.substring(context.length());
            }
            return url;
        }).collect(Collectors.toSet()));
        noAuthCache.put(formId, cacheUrls);
    }

    public void putNoAuth(String url) {
        noAuthUrls.add(url);
    }
}
